<template>
	<div class="input_number">
		<input
			class="input_number-input"
			:value="currentValue"
			@input="handlerInput" />
		<div>
			<button
				class="input_number_btn input-number__btn-plus"
				@click="setCurrentValue(1)"
				:disabled="currentValue >= max">
				+
			</button>
			<button
				class="input_number_btn"
				@click="setCurrentValue(-1)"
				:disabled="currentValue <= min">
				-
			</button>
		</div>
	</div>
</template>

<script>
import debounce from 'lodash/debounce'
export default {
	name: 'InputNumber',
	props: {
		// 商品数量
		value: {
			type: Number,
			default: 1,
		},
		// 最大值
		max: {
			type: Number,
			default: 10,
		},
		// 最小值
		min: {
			type: Number,
			default: 1,
		},
	},
	data() {
		return {
			currentValue: this.value,
		}
	},
	methods: {
		// 点击加 减
		setCurrentValue(value) {
			this.currentValue += value
		},
		handlerInput: debounce(function (e) {
			// +转换成Number ：收集数据是字符串 value设置类型是Number 会报错
			this.currentValue = +e.target.value
		}, 500),
	},
	watch: {
		currentValue(newValue, oldValue) {
			const { min, max } = this
			let currentValue = newValue
			// 设置边距数量
			if (currentValue < min) {
				currentValue = min
			} else if (currentValue > max) {
				currentValue = max
			}
			// 判断用户输入的值是不是合法的，不是就使用上一次的值
			if (Number.isNaN(currentValue)) {
				currentValue = oldValue
			}

			this.currentValue = currentValue
			// 这里触发组件的v-model  使用'input'可以触发，第二个参数传的要修改的值
			this.$emit('input', this.currentValue)
		},
		value(newVal) {
			this.currentValue = newVal
		},
	},
}
</script>

<style lang="less" scoped>
.input_number {
	display: flex;
	border: 1px solid #ccc;
	width: 60px;
}
.input_number-input {
	width: 40px;
	height: 40px;
	outline: none;
	text-align: center;
	border: 0;
}
.input_number_btn {
	width: 20px;
	height: 20px;
	border-top: 0;
	border-right: 0;
	border-bottom: 0;
	border-left: 1px solid #ccc;
	&:disabled {
		cursor: no-drop;
		color: #ccc;
	}
}
.input-number__btn-plus {
	border-bottom: 1px solid #ccc;
}
</style>
